package org.pjx.spm.service;

import org.pjx.spm.mapper.Work_attendanceMapper;
import org.pjx.spm.pojo.Employee_Salary;
import org.pjx.spm.pojo.Work_attendance;
import org.pjx.spm.util.interfacespecfiaction.RespBean;
import org.pjx.spm.util.timeboundCheck.TimeBoundCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author Glow
 * @Date 2022-03-16 15:57:16
 * @Description
 * @Version 1.0
 */
@Service
public class Work_attendanceServiceImpl implements  Work_attendanceService {
    @Autowired
   private  Work_attendanceMapper work_attendanceMapper;
@Autowired
private Employee_SalaryServiceImpl employee_salaryService;
@Autowired
private UserServiceImpl userService;
    /**
     * 给出所有考勤记录并动态刷新
     * @return
     */
    @Override
    public List<Work_attendance> selectAllWorkAttendance() {
        List<Work_attendance> list = work_attendanceMapper.selectAllWorkAttendance();
        Date date = new Date();
        System.out.println(date);
        ListIterator<Work_attendance> iterator =list.listIterator();
//        ListIterator<Work_attendance> iterators =list.listIterator();
//            while (iterators.hasNext())
//            {
//                System.out.println(iterators.next());
//            }
        while(iterator.hasNext())
            {
                Work_attendance work_attendance = iterator.next();
                if(work_attendance.getAttendcheckdate()==null
                        &&work_attendance.getChecktype().equals("0")
                        &&work_attendance.getAttendtype().equals("上班"))
                {

                    if(!TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate()))
                    {System.out.println("上班你没签到");
                        work_attendance.setChecktype("4");
                        work_attendanceMapper.UpdateSetChecktype(work_attendance);
                    }
                }
                else if(work_attendance.getAttendcheckdate()==null
                        &&work_attendance.getChecktype().equals("0")
                        &&work_attendance.getAttendtype().equals("下班"))
                {

                    if(!TimeBoundCheck.AutoCheckIsEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate()))
                    {System.out.println("下班你没签到");
                        work_attendance.setChecktype("4");
                        work_attendanceMapper.UpdateSetChecktype(work_attendance);
                    }

                }
//                if(work_attendance.ge)
                iterator.set(work_attendance);
                System.out.println(work_attendance);
            }
//        list = se
        return list;
    }

    @Override
    public List<Work_attendance> selectAllWorkAttendanceByDepartmentId(String departmentId) {
        return work_attendanceMapper.selectAllWorkAttendanceByDepartmentId(departmentId);
    }

    @Override
    public List<Work_attendance> selectAllWorkAttendanceByDepartmentIdThisMonth(String departmentId, String checkdate) {
        return work_attendanceMapper.selectAllWorkAttendanceByDepartmentIdThisMonth(departmentId,checkdate);
    }

    @Override
    public Work_attendance selectAllWorkAttendanceByAttendance(Integer attendance) {
        return work_attendanceMapper.selectAllWorkAttendanceByAttendance(attendance);
    }

    @Override
    public List<Work_attendance> selectAllWorkAttendanceAscBycheckstartdate() {
        return work_attendanceMapper.selectAllWorkAttendanceAscBycheckstartdate();
    }

    @Override
    public List<Work_attendance> selectAttendByCheckdate(String checkdate) {
        return work_attendanceMapper.selectAttendByCheckdate(checkdate);
    }

    @Override
    public List<Work_attendance> selectAttendByCheckdateAndDepId(String checkdate, String departmentId) {
        return work_attendanceMapper.selectAttendByCheckdateAndDepId(checkdate, departmentId);
    }

    public List<Work_attendance> selectAllAttendByCheckdateAndDepId(String checkdate,String departmentId) {
        return work_attendanceMapper.selectAttendByCheckdateAndDepId(checkdate,departmentId);
    }
    @Override
    public int UpdateSetChecktype(Work_attendance work_attendance) {
        return work_attendanceMapper.UpdateSetChecktype(work_attendance);
    }

    /**
     * 查询所有职员员工（用来选择创建考勤打卡）
     * @return
     */
    @Override
    public List<Map<String, String>> selectAllEmpUserIdAndUsername() {
        List<Map<String, String>> list = work_attendanceMapper.selectAllEmpUserIdAndUsername();
        for(Map<String, String>map:list)
        {
            System.out.println("userId:"+map.get("userId")+";username:"+map.get("username"));

        }
        return list;
    }

    @Override
    public List<Map<String, String>> selectAllDepEmpUserIdAndUsername(Integer departmentId) {
        return work_attendanceMapper.selectAllDepEmpUserIdAndUsername(departmentId);
    }

    public List<Map<String, String>> selectDepEmpUserIdAndUsername(Map<String,Integer> maps) {
        List<Map<String, String>> list = work_attendanceMapper.selectAllDepEmpUserIdAndUsername(maps.get("departmentId"));
        for(Map<String, String>map:list)
        {
            System.out.println("userId:"+map.get("userId")+";username:"+map.get("username"));

        }
        return list;
    }
    @Override
    public int InsertNewAttendance(Work_attendance work_attendance) {
        return work_attendanceMapper.InsertNewAttendance(work_attendance);
    }

    @Override
    public int UpdateAttendanceByattendance(Work_attendance work_attendance) {
        return work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
    }

    @Override
    public int DeleteWorkAttendanceByattendance(Integer attendance) {
        return work_attendanceMapper.DeleteWorkAttendanceByattendance(attendance);
    }

    @Override
    public List<Work_attendance> selectAttendanceByIdAndCheckDate(String userId, String checkdate) {
        return work_attendanceMapper.selectAttendanceByIdAndCheckDate(userId,checkdate);
    }

    @Override
    public int updateIssearchByAttendance(Integer attendance, Integer issearch) {
        return work_attendanceMapper.updateIssearchByAttendance(attendance, issearch);
    }

    @Override
    public int selectissearchByAttendance(Integer attendance) {
        return work_attendanceMapper.selectissearchByAttendance(attendance);
    }

    @Override
    public List<Work_attendance> selectAllWorkAttendanceAscBycheckstartdateByThisMonth(String checkdate) {
        return work_attendanceMapper.selectAllWorkAttendanceAscBycheckstartdateByThisMonth(checkdate);
    }

    @Override
    public List<Work_attendance> selectMonthAttendanceByuserId(String userId, String checkdate) {
        return work_attendanceMapper.selectMonthAttendanceByuserId(userId, checkdate);
    }

    @Override
    public List<Work_attendance> selectDayAttendanceByuserId(String userId, String checkdate) {
        return work_attendanceMapper.selectDayAttendanceByuserId(userId, checkdate);
    }
    @Override
    public List<Work_attendance> selectDayAttendanceByuserIdAndDepId(String userId, String checkdate,String departmentId) {
        return work_attendanceMapper.selectDayAttendanceByuserIdAndDepId(userId, checkdate,departmentId);
    }

    @Override
    public Double selectBaseSalaryFromEmp(String userId) {
        return work_attendanceMapper.selectBaseSalaryFromEmp(userId);
    }

    public RespBean DeleteWorkAttendanceByattendances(Map<Object,Object>map)
    {
       System.out.println(map.get("attendances").toString().substring(1,map.get("attendances").toString().length()-1));
       String Deleteattendance[]=map.get("attendances").toString().substring(1,map.get("attendances").toString().length()-1).split(", ");

        if(!map.get("attendances").toString().equals("[]"))
        {
            for(int i = 0; i <Deleteattendance.length;i++)
            {

                System.out.println(Deleteattendance[i]);
                int issearch = work_attendanceMapper.selectissearchByAttendance(Integer.valueOf(Deleteattendance[i]));
                System.out.println(issearch);
                if(issearch == 0)
                {
                    work_attendanceMapper.DeleteWorkAttendanceByattendance( Integer.valueOf(Deleteattendance[i]));
                }
                else {
                    return RespBean.error("删除失败，此已被记录");
                }

            }
            return RespBean.ok("删除成功");
        }
        else {
            return RespBean.error("删除失败");
        }

    }
    public RespBean createNewAttendance(Map<Object,Object> map){
        Work_attendance work_attendance = new Work_attendance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormatYear = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
            String Id = map.get("Ids").toString().substring(1,map.get("Ids").toString().length()-1);
            String[] Ids = Id.split(", ");
            String name = map.get("Names").toString().substring(1,map.get("Names").toString().length()-1);
            String names[]=name.split(", ");

        try{

            work_attendance.setCheckdate(simpleDateFormatYear.parse(map.get("checkdate").toString()));
            String times = map.get("checkstartdate").toString().substring(11);
            work_attendance.setCheckstarttime(simpleDateFormatTime.parse(times));
            times = map.get("checkenddate").toString().substring(11);
            work_attendance.setCheckendtime(simpleDateFormatTime.parse(times));
            work_attendance.setCheckstartdate(simpleDateFormat.parse(map.get("checkstartdate").toString()));
            work_attendance.setCheckenddate(simpleDateFormat.parse(map.get("checkenddate").toString()));
            work_attendance.setCreatedate(simpleDateFormat.parse(map.get("createdate").toString()));
            work_attendance.setAttendtype(map.get("attendtype").toString());

            for(int i = 0 ; i < names.length; i++)
            {
                work_attendance.setUserId(Ids[i]);
                work_attendance.setUsername(names[i]);
               String findDate = sf.format(work_attendance.getCheckdate())+"%";
               System.out.println(findDate);
               List<Employee_Salary> employee_salaryList =employee_salaryService.
                       SelectAllEmployeeSalaryByuserIdAndSalaryMonthDescBysalaryMonth
                               (work_attendance.getUserId(),findDate);

               if(employee_salaryList.toString().equals("[]"))
               {
                   String role = userService.selectroleByuserId(work_attendance.getUserId());
                   System.out.println();
                   System.out.println("role:"+role);
                   System.out.println(employee_salaryList.toString());
                   Employee_Salary employee_salary = new Employee_Salary();
                   employee_salary.setUserId(work_attendance.getUserId());
                   employee_salary.setUsername(work_attendance.getUsername());
                   employee_salary.setRole(role);
                   employee_salary.setSalaryMonth(sf.format(work_attendance.getCheckdate()));
                   employee_salary.setBaseSalary(work_attendanceMapper.selectBaseSalaryFromEmp(work_attendance.getUserId()));
                   employee_salaryService.InsertEmployeeSalaryInIt(employee_salary);
               }
                System.out.println(work_attendance.toString());
                work_attendanceMapper.InsertNewAttendance(work_attendance);
            }

        }catch (ParseException e)
        {
            e.printStackTrace();
            return RespBean.error("插入错误~清重试~");
        }

        return RespBean.ok("test");
    }
        public RespBean UpdateAttendcheckdate(Work_attendance work_attendance) throws ParseException {
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            cal.setTime(work_attendance.getCheckenddate());
            cal.add(Calendar.MINUTE,30);
            Date dates = cal.getTime();
            if(work_attendance.getAttendtype().equals("下班"))
            {
                if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate())&&work_attendance.getChecktype().equals("0"))
                {
//                    如果是下班类别且是正常时间内，状态为1
                    work_attendance.setChecktype("1");
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("签到成功");
                }
//                请假
                else  if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate())&&work_attendance.getChecktype().equals("2"))
                {
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("请假成功");
                }
//                迟到补签 超过半小时则失败
                else if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckenddate(),dates)&&work_attendance.getChecktype().equals("4"))
                {

                    work_attendance.setChecktype("3");
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("补签成功！下次别忘记了哦~");
                }
//                加班，前提是前面正常打卡~
                else if(work_attendance.getChecktype().equals("1"))
                {
                    System.out.println("最晚打卡时间开始计时："+work_attendance.getCheckenddate().toString());
                    System.out.println("当前打卡时间为："+date);

                    String fromDate = simpleDateFormat.format(work_attendance.getCheckenddate());
                    String toDate = simpleDateFormat.format(date);
                    long from = simpleDateFormat.parse(fromDate).getTime();
                    long to = simpleDateFormat.parse(toDate).getTime();
                    int hours = (int) ((to - from)/(1000 * 60 * 60));
                    if(hours<0)
                    {
                        return RespBean.error("时间异常");
                    }
                    work_attendance.setWorkhour((Integer)hours);
                    work_attendance.setAttendcheckdate(date);
                    work_attendance.setChecktype("6");
                    System.out.println(hours);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("打工成功，加班辛苦了！");
                }
//                下班想早退？没门~
                 else if(!TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate())&&work_attendance.getChecktype().equals("0"))
                {
                    work_attendance.setChecktype("5");
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("你早退了！");
                }

            }
            if(work_attendance.getAttendtype().equals("上班"))
            {
                if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate())&&work_attendance.getChecktype().equals("0"))
                {
//                    如果是上班类别且是正常时间内，状态为1
                    work_attendance.setChecktype("1");
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("签到成功");
                }
//                请假
                else  if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckstartdate(),work_attendance.getCheckenddate())&&work_attendance.getChecktype().equals("2"))
                {
                    work_attendance.setAttendcheckdate(date);
                    work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                    return RespBean.ok("请假成功");
                }
//                迟到补签 超过半小时则失败
                else if(TimeBoundCheck.isEffectiveDate(date,work_attendance.getCheckenddate(),dates)&&work_attendance.getChecktype().equals("4"))
                {
                    Integer ismodify = work_attendanceMapper.selectissearchByAttendance(work_attendance.getAttendance());
                    if(ismodify ==0)
                    {
                        work_attendance.setChecktype("3");
                        work_attendance.setAttendcheckdate(date);
                        work_attendanceMapper.UpdateAttendanceByattendance(work_attendance);
                        return RespBean.ok("补签成功！下次别迟到了哦~");
                    }
                    else if(ismodify ==1) {
                        System.out.println("已经被系统录制考勤信息，无法更改状态");
                        return RespBean.error("补签失败！已被系统记录！");
                    }

                }
            }

            return RespBean.error("签到异常，清重试");
        }
}
